package jmind.core.jdbc;

import javax.sql.DataSource;

import jmind.base.lang.IProperties;
import jmind.base.util.DataUtil;

/**
 * @author weibo.xwb
 */
public class HikariDataSource  extends DataSourceFactory{

    @Override
    public DataSource getSource(String name, IProperties p) {
        /**
         * <property name="driverClassName" value="com.mysql.jdbc.Driver" />
        <property name="url" value="${jdbc.url}" />
        <property name="username" value="${jdbc.user}" />
        <property name="password" value="${jdbc.password}" />
        <property name="maxIdle" value="10" />
        <!-- 300秒回收不用的连接 -->
        <property name="removeAbandoned" value="true" />
        <property name="removeAbandonedTimeout" value="300" />
        <!-- MySQL8小时问题 -->
        <property name="validationQuery" value="SELECT 1" />
        <property name="testOnBorrow" value="false" />
        <property name="testOnReturn" value="false" />
        <property name="testWhileIdle" value="true" />
        <property name="timeBetweenEvictionRunsMillis" value="300000" />
        <property name="numTestsPerEvictionRun" value="3" />
        <property name="minEvictableIdleTimeMillis" value="1800000" />
        
         */
        String url = p.getProperty("jdbc." + name + ".url");
        System.out.println("jdbc." + name + ".url=" + url);
        if (DataUtil.isEmpty(url)) {
            return null;
        }
        com.zaxxer.hikari.HikariDataSource ds = new com.zaxxer.hikari.HikariDataSource();
        ds.setJdbcUrl(url);
        String driverClassName = "com.mysql.cj.jdbc.Driver";
        if (url.startsWith("jdbc:oracle")) {
            driverClassName = "oracle.jdbc.driver.OracleDriver";
            //    ds.setConnectionTestQuery("SELECT * FROM DUAL");
        } else if (url.startsWith("jdbc:sqlserver")) {
            driverClassName = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
        } else {
            //   ds.setConnectionTestQuery("SELECT 1");
        }
        ds.setDriverClassName(driverClassName);
        ds.setUsername(p.getProperty("jdbc." + name + ".username"));
        ds.setPassword(p.getProperty("jdbc." + name + ".password"));
        // 最大空闲数
        ds.setMinimumIdle(DataUtil.toInt(p.getProperty("jdbc." + name + ".maxIdle", "1")));
        // 最大活跃数
        int maxActive = DataUtil.toInt(p.getProperty("jdbc." + name + ".maxActive", "20"));
        ds.setMaximumPoolSize(maxActive);
        // slave
        ds.setReadOnly(Boolean.parseBoolean(p.getProperty("jdbc." + name + ".slave")));

        return ds;

    }

}
